package ift604.projet.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.List;

import org.apache.http.NameValuePair;

/**
 * 
 * Classe utilitaire pour realiser des requetes HTTP telles que GET et POST
 *
 */
public class HTTPUtil
{
	/**
	 * A partir d'une liste de parametres attribut/valeur, forme la chaine de caractere
	 * allant a droite du "?" dans l'adresse
	 */
	public static String paramsEnPhrase(List<NameValuePair> params) {
		String requestParams = "";
		for (int i = 0; i < params.size(); i++) {
			NameValuePair pair = params.get(i);
			if (i > 0)
				requestParams += "&";

			try {
				requestParams += pair.getName()+"="+URLEncoder.encode(pair.getValue(), "UTF-8");
			}
			catch (Exception e) {
				e.printStackTrace();
			}
		}

		return requestParams;
	}

	/**
	 * Envoie une requete GET vers adresse, en utilisant les parametres attribut/valeur params
	 * Retourne la reponse en format String
	 */
	public static String sendGETRequest(String adresse, List<NameValuePair> params)
	{
		String requestParams = paramsEnPhrase(params);
		return sendGetRequest(adresse, requestParams);
	}


	/**
	 * Envoie une requete GET vers adresse, en utilisant les parametres en format String params
	 * Retourne la reponse en format String
	 */
	public static String sendGetRequest(String adresse, String params) {
		String result = null;
		try
		{
			// envoi de la requete
			String urlStr = adresse;
			if (params != null && params.length () > 0) {
				urlStr += "?" + params;
			}
			URL url = new URL(urlStr);
			URLConnection conn = url.openConnection ();

			// reception de la reponse
			BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			StringBuffer sb = new StringBuffer();
			String line;
			while ((line = rd.readLine()) != null) {
				sb.append(line);
			}
			rd.close();
			result = sb.toString();
		} 
		catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * Envoie une requete POST vers adresse, en utilisant les parametres attribut/valeur params
	 * Retourne la reponse en format String
	 */
	public static String postData(String adresse, List<NameValuePair> params) {
		StringWriter sw = null;

		HttpURLConnection urlc = null;
		OutputStream out = null;
		InputStream in = null;
		try	{
			// configuration de la requete
			URL url = new URL(adresse);
			urlc = (HttpURLConnection) url.openConnection();
			urlc.setRequestMethod("POST");
			urlc.setDoOutput(true);
			urlc.setDoInput(true);
			urlc.setUseCaches(false);
			urlc.setAllowUserInteraction(false);
			urlc.setRequestProperty("Content-type", "text/xml; charset=" + "UTF-8");

			// envoi de la requete
			out = urlc.getOutputStream();
			Writer writer = new OutputStreamWriter(out, "UTF-8");
			writer.write(paramsEnPhrase(params));
			writer.close();
			out.close();

			// reception de la reponse
			sw = new StringWriter();
			in = urlc.getInputStream();
			Reader reader = new InputStreamReader(in);
			pipe(reader, sw);
			reader.close();
			in.close();
			
			urlc.disconnect();
		} catch (IOException e)	{
			e.printStackTrace();
		} 

		if (sw == null)
			return null;
		return sw.getBuffer().toString();
	}

	/**
	 * Copie les donnees de reader vers writer
	 */
	private static void pipe(Reader reader, Writer writer) throws IOException {
		char[] buf = new char[1024];
		int read = 0;
		while ((read = reader.read(buf)) >= 0)
		{
			writer.write(buf, 0, read);
		}
		writer.flush();
	}
}


